from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class SystemLog(models.Model):
    """系统操作日志模型"""
    ACTION_CHOICES = [
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('login', '登录'),
        ('logout', '退出'),
        ('view', '查看'),
        ('upload', '上传'),
        ('download', '下载'),
    ]
    
    user = models.ForeignKey('user.SysUser', on_delete=models.CASCADE, related_name='logs', verbose_name='操作用户')
    action = models.CharField(max_length=20, choices=ACTION_CHOICES, verbose_name='操作类型')
    content = models.TextField(verbose_name='操作内容')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')
    user_agent = models.TextField(null=True, blank=True, verbose_name='用户代理')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    
    class Meta:
        db_table = 'dashboard_system_log'
        verbose_name = '系统日志'
        verbose_name_plural = '系统日志'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.user.username} - {self.get_action_display()} - {self.created_at.strftime("%Y-%m-%d %H:%M:%S")}'


class SystemMetrics(models.Model):
    """系统性能指标模型"""
    cpu_usage = models.FloatField(verbose_name='CPU使用率(%)')
    memory_usage = models.FloatField(verbose_name='内存使用率(%)')
    disk_usage = models.FloatField(verbose_name='磁盘使用率(%)')
    network_in = models.BigIntegerField(default=0, verbose_name='网络入流量(字节)')
    network_out = models.BigIntegerField(default=0, verbose_name='网络出流量(字节)')
    timestamp = models.DateTimeField(default=timezone.now, verbose_name='记录时间')
    
    class Meta:
        db_table = 'dashboard_system_metrics'
        verbose_name = '系统指标'
        verbose_name_plural = '系统指标'
        ordering = ['-timestamp']
    
    def __str__(self):
        return f'系统指标 - {self.timestamp.strftime("%Y-%m-%d %H:%M:%S")}'


class QuickAction(models.Model):
    """快速操作配置模型"""
    title = models.CharField(max_length=100, verbose_name='操作标题')
    description = models.CharField(max_length=200, verbose_name='操作描述')
    icon = models.CharField(max_length=50, verbose_name='图标名称')
    color_class = models.CharField(max_length=50, verbose_name='颜色类名')
    route = models.CharField(max_length=200, verbose_name='路由地址')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    sort_order = models.IntegerField(default=0, verbose_name='排序')
    required_permission = models.CharField(max_length=100, null=True, blank=True, verbose_name='所需权限')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    
    class Meta:
        db_table = 'dashboard_quick_action'
        verbose_name = '快速操作'
        verbose_name_plural = '快速操作'
        ordering = ['sort_order', '-created_at']
    
    def __str__(self):
        return self.title